<?php
namespace timer_job\common\helper;

class Curl {
    public function simple($url){
        if (empty($url)) {
            return false;
        }
        // 1. 初始化
        $ch = curl_init();
        // 2. 设置选项，包括URL
        curl_setopt($ch,CURLOPT_URL,$url);
        curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
        curl_setopt($ch,CURLOPT_HEADER,0);
        // 3. 执行并获取HTML文档内容
        $output = curl_exec($ch);
        if($output === FALSE ){
            return false;
        }
        // 4. 释放curl句柄
        curl_close($ch);
        return $output;
    }

    /**
     * @param $url
     * @param $data
     * @param int $timeout
     * @return bool|mixed
     */
    public function getCurl($url, $data, $timeout = 30){
        if($url == "" || $timeout <= 0){
            return false;
        }
        $url = $url.'?'. http_build_query($data);
        $ch = curl_init((string)$url);
        curl_setopt($ch, CURLOPT_HEADER, false);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER,true);
        curl_setopt($ch, CURLOPT_TIMEOUT, (int)$timeout);

        try {
            $res = curl_exec($ch);
            if ($res === false) {
                return false;
            }
            curl_close($ch);
        } catch (\Exception $e) {
            return false;
        }
        return $res;
    }

    public function postCurl($url,$data,$timeout = 30){
        if(empty($url) || empty($data) || $timeout <=0){
            return false;
        }
        if (is_array($data)) {
            $data = http_build_query($data);
        }
        $ch = curl_init((string)$url);
        curl_setopt($ch, CURLOPT_HEADER, false);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        curl_setopt($ch, CURLOPT_POST,true);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER,true);
        curl_setopt($ch, CURLOPT_TIMEOUT,(int)$timeout);

        $res = curl_exec($ch);
        if ($res === false) {
            return false;
        }
        curl_close($ch);
        return $res;
    }


}